import { createStore } from "vuex";
import axios from "axios";

const store = createStore({
  state() {
    return {
      sellerIofo: {},
      goods: [],
      show: false,
      carList: [],
      price: 0,
    
    };
  },
  getters: {
    getPrice(state) {
      // let num = 0;
      // state.carList.forEach((item) => {
      //   num += item.price * item.count;
      // });
      // return num;
    },
  },
  mutations: {
    clearList(state){
      state.carList.forEach((item)=>{
        item.count=0;
      })
      state.carList=[];
      state.show=false;
     
    },
    setSeller(state, payload) {
      state.sellerIofo = payload.data;
    },
    setGoods(state, payload) {
      console.log(payload)
      state.goods = payload.data;
    },
    showCar(state){
      state.show = !state.show;
    },
    setCarList(state, payload){
      console.log(payload)
      const hasItem = state.carList.findIndex((item) => {
        return item.name == payload.item.name;
      });
      console.log(hasItem)
      if (hasItem == "-1") {
        state.carList.push(payload.item);
      }

      //   state.carList.forEach((item) => {
      //     if (item.name == payload.item.name) {
      //       return false;
      //     } else {
      //       state.carList.push(payload.item);
      //     }
      //   });
      // } else {
      //   console.log("-");

      //   state.carList.push(payload.item);
      // }
      // console.log(state.carList);
    },
  },
  actions: {
    async getGoods({ commit }) {
      const {data:{data}}
       = await axios.get("/api/goods");
      console.log(data)
      commit("setGoods", {data} );
      // console.log(data)
      // const newArr = [];
      // data.forEach((item) => {
      //   let foodsList = [];
      //   item.foods.forEach((food) => {
      //     foodsList.push({
      //       name: food.name,
      //       count: 0,
      //       price: food.price,
      //       sellCount: food.sellCount,
      //       icon: food.icon,
      //       image: food.image,
      //     });
      //   });

      //   newArr.push({
      //     name: item.name,
      //     foods: foodsList,
      //   });
      // });
      // console.log(newArr, "news------------------");
    },
    async getSeller({ commit }) {
      const {
        data: { data },
      } = await axios.get("/api/seller");

      commit("setSeller", {
        data,
      });
    },
  },
});

export default store;
